package com.endava.spring_ioc.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.endava.spring_ioc.beans.Account;
import com.mysql.jdbc.PreparedStatement;

/**
 * The implementation of <code>AccountDao</code> interface.
 * 
 * @author acojocar
 * @since 26.07.2013
 * @version 1.0
 * 
 */
public class AccountDaoImplementation implements AccountDao {

	private List<Account> accounts;

	/**
	 * Constructor. Initialize a list of accounts.
	 */
	public AccountDaoImplementation() {
		super();
		accounts = new ArrayList<Account>();
	}

	@Override
	public ResultSet getAllAccounts() {
		Statement statement = null;
		ResultSet rs = null;

		try {
			statement = DataBase.getInstance().getDB().createStatement();
			rs = statement.executeQuery(SELECT_TABLE + ACCOUNT_TABLE);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return rs;
	}

	@Override
	public void addAccount(Integer accountID, String accountType, Integer amount) {
		PreparedStatement statement;

		try {
			statement = (PreparedStatement) DataBase
					.getInstance()
					.getDB()
					.prepareStatement(
							"INSERT INTO " + ACCOUNT_TABLE
									+ " VALUES(?, ?, ?);");
			statement.setInt(1, accountID);
			statement.setString(2, accountType);
			statement.setInt(3, amount);
			statement.execute();

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void deleteAccount(Integer accountID) {
		Statement statement = null;
		try {
			statement = DataBase.getInstance().getDB().createStatement();
			statement.executeUpdate("DELETE FROM " + ACCOUNT_TABLE
					+ " WHERE id_account = " + accountID);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<Account> getAccounts() {
		return accounts;
	}

	@Override
	public int addAccount(Account account) {
		accounts.add(account);
		return accounts.size();
	}

	@Override
	public ResultSet getAccountByID(Integer accountID) {
		Statement statement;
		ResultSet rs = null;
		try {
			statement = DataBase.getInstance().getDB().createStatement();
			rs = statement.executeQuery("SELECT * FROM " + ACCOUNT_TABLE
					+ " WHERE id_account = " + accountID);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

}
